<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import { computed, ref } from 'vue';
import { notification } from 'ant-design-vue';

import { useVbenModal } from '@vben/common-ui'; // Changed from useVbenDrawer
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { createRole, getRole, updateRole } from '#/api/abp/role';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { formSchema } from './data'; // Using the same schema for now

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: formSchema(), // Using the same schema
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({ // Changed from useVbenDrawer and drawerApi
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  destroyOnClose: true,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true); // Changed from drawerApi.drawerLoading
    const { id } = modalApi.getData() as { id?: string }; // Changed from drawerApi.getData
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await getRole(id);
      await formApi.setValues(record);
    }

    await markInitialized();
    modalApi.modalLoading(false); // Changed from drawerApi.drawerLoading
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true); // Changed from drawerApi.lock

    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    const data = cloneDeep(await formApi.getValues());

    await (isUpdate.value ? updateRole(data.id, data) : createRole(data));
    emit('reload');
    resetInitialized();
    modalApi.close(); // Changed from drawerApi.close

    notification.success({
      duration: 2,
      message: isUpdate.value ? $t('pages.common.editSuccess') : $t('pages.common.addSuccess'),
    });
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false); // Changed from drawerApi.lock
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

// Expose modalApi for parent component to control the modal
defineExpose({
  modalApi,
});
</script>

<template>
  <BasicModal :title="title" class="w-[600px]">
    <BasicForm />
  </BasicModal>
</template>
